<template>
	<view>
		<scroll-view scroll-x class="bg-white nav fixed">
			<view class="flex text-center">
				<view class="cu-item flex-sub" :class="index==TabCur?'text-blue cur':''" v-for="(item,index) in list" :key="index"
				 @tap="tabSelect" :data-id="index">
					{{item}}
				</view>
			</view>
		</scroll-view>
		<block v-if="TabCur==0">
			<view style="margin-top: 110rpx;">
				<view class="indextit">说明：若访客信息较多，可选择导入excel模板。</view>
				<view class="template-wrapper">
					<view class="btns">
						<button class="btn1" data-clipboard-action="copy" data-clipboard-text="https://bwclf.ustc.edu.cn/word/入校模板.xlsx" type="default" size="mini">
							<svg t="1681471403664" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2685" width="32" height="32"><path d="M544.256 605.184l244.224-244.224a31.744 31.744 0 0 1 45.056 45.056l-295.424 295.424a36.864 36.864 0 0 1-51.2 0L190.464 406.528a31.744 31.744 0 1 1 45.056-45.056l244.224 244.224V111.104a32.256 32.256 0 1 1 64 0zM153.6 902.656a32.256 32.256 0 0 1 0-64h716.8a32.256 32.256 0 0 1 0 64z" fill="#ffffff" p-id="2686"></path></svg>
							下载excel模板
						</button>
						<button type="default" size="mini" @click="uploadExcel">
							<svg t="1681471471003" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3844" width="32" height="32"><path d="M153.6 902.656a32.256 32.256 0 0 1 0-64h716.8a32.256 32.256 0 0 1 0 64z m390.656-665.6v494.592a32.256 32.256 0 0 1-64 0V237.056L236.032 481.28a31.744 31.744 0 1 1-45.056-45.056l294.912-295.424a36.864 36.864 0 0 1 51.2 0l294.912 294.912a31.744 31.744 0 0 1-45.056 45.056z" fill="#ffffff" p-id="3845"></path></svg>
							上传excel模板
						</button>
					</view>
					<view class="temp-tip">
						<view>操作步骤 :</view>
						<view class="line">步骤一：点击下载excel模板按钮，自动复制链接；</view>
						<view class="line">步骤二：打开浏览器粘贴访问，下载excel模板；</view>
						<view class="line">步骤三：填完保存后，点击导入excel模板按钮 ，导入表格，系统自动填充访客信息。</view>
						<view class="line">注：每次申请来访人员不得超过20人。</view>
					</view>
				</view>
				<form>
					<view class="cu-form-group">
						<view class="title"><text class="text-red">*</text>邀请码</view>
						<input placeholder="请输入邀请码" name="input" v-model.trim="userForm.inviteCode" @blur="getInfoByCode"></input>
					</view>
					<view class="text-red" style="margin: 20rpx;">注意：请输入在校教职工分享的邀请码，单个邀请码仅限使用1次。</view>
					<view class="indextit">人员信息</view>
					<view v-for="(num,index) in userForm.userInfo" :key="index">
						<view class="cu-form-group" style="marginTop:10rpx;">
							<view class="title"  @click="chooseImg"><text class="text-red">*</text>来访人</view>
							<input :disabled="index===0" placeholder="请输入校外拟入校人员姓名" @click="disableInput=false" name="input" v-model.trim="num.userName"></input>
							<text class='cuIcon-delete text-red' @click="delUser(index)" v-if="userForm.userInfo.length>1 && index>0"></text>
						</view>

						<view class="cu-form-group">
							<view class="title"><text class="text-red">*</text>证件类型</view>
							<picker @change="bindType" @cancel="clear" :value="typeindex" :range="carType" range-key="name" :data-id="index">
								<view class="picker">
									{{num.carTypeName || '请选择证件类型'}}
								</view>
							</picker>
						</view>
						<view class="cu-form-group">
							<view class="title"><text class="text-red">*</text>证件号码</view>
							<input placeholder="请输入证件号码" name="input" v-model.trim="num.cardNo"></input>
						</view>
						<view class="cu-form-group">
							<view class="title"><text class="text-red">*</text>联系电话</view>
							<input :disabled="index===0" placeholder="请输入联系电话" type="number" name="input" v-model.trim="num.userPhone"></input>
						</view>
						<view class="cu-form-group">
							<view class="title"><text class="text-red">*</text>是否有车辆</view>
							<view style="flex: 1;">
								<radio-group @change="chooseHasCar(num)">
									<label class="radio"><radio :value="0" color="#004D95" :checked="num.hasCar===0" /> <text style="margin-left: 10rpx;">否</text></label>
									<label class="margin-left"><radio :value="1" color="#004D95"  :checked="num.hasCar===1" /> <text style="margin-left: 10rpx;">是</text></label>
								</radio-group>
							</view>
						</view>
						<template v-if="num.hasCar===1">
							<view class="cu-form-group" @click.prevent="carInputClick(index,num.carNumber)">
								<view class="title"><text class="text-red">*</text>车辆号码</view>
								<view style="flex: 1;" class="carnumber">{{num.carNumber || '请输入车牌号'}}
									<!-- <image :src="energy" mode="" v-show="num.carNumber!=='请输入车牌号'&& num.carNumber.length>7"/> -->
								</view>
							</view>
							<view class="cu-form-group">
								<view class="title"><text class="text-red">*</text>车型选择</view>
								<picker @change="CarModelChange" @cancel="clear" :value="carIndex" :range="CarModelList" range-key="name"
								 :data-id="index" >
									<view class="picker">
										{{num.carModelName || '请选择车型'}}
									</view>
								</picker>
							</view>
						</template>
					</view>
					<view class="text-blue btn-add" @click="addUser">
						<text class="cuIcon-add"></text>
						<text>添加人员</text>
					</view>
					<view class="cu-form-group" style="marginTop:15rpx;" >
						<view class="title"><text class="text-red">*</text>校内接待部门</view>
						<input disabled placeholder="请选择接待部门名称" name="input" v-model="userForm.departName"></input>
					</view>
					<view class="cu-form-group" >
						<view class="title"><text class="text-red">*</text>审核人员</view>
						<input disabled placeholder="请选择审核人员" name="input" v-model="userForm.checkUserName"></input>
					</view>

					<view class="cu-form-group">
						<view class="title"><text class="text-red">*</text>校内联系人</view>
						<input  placeholder="请输入校内联系人" disabled name="input" v-model="userForm.concatName"></input>
					</view>
					<view class="cu-form-group">
						<view class="title" style="height: auto;margin: 12rpx 0;">
							<text class="text-red">*</text>
							<text>
								<text style="display: inline-block;">校内联系人</text>
								<text style="display: inline-block;">GID号</text>
							</text>
						</view>
						<input disabled name="input" v-model="userForm.concatGid"></input>
					</view>
					<view class="cu-form-group">
						<view class="title" style="height: auto;margin: 12rpx 0;">
							<text class="text-red">*</text>
							<text>
								<text style="display: inline-block;">校内联系人</text>
								<text style="display: inline-block;">工资号</text>
							</text>
						</view>
						<input disabled name="input" v-model="userForm.concatWage"></input>
					</view>
					<view class="cu-form-group">
						<view class="title"><text class="text-red">*</text>联系电话</view>
						<input disabled placeholder="请输入校内联系人电话" name="input" type="number" v-model="userForm.concatPhone"></input>
					</view>
					<view class="cu-form-group" style="marginTop:15rpx;">
						<view class="title"><text class="text-red">*</text>校区</view>
						<input disabled placeholder="请选择校区" name="input" v-model="userForm.campus"></input>
					</view>

					<view class="cu-form-group" >
						<view class="title"><text class="text-red">*</text>入校日期</view>
						<input disabled placeholder="请选择日期区间" name="input" v-model="userFormDateRange"></input>
					</view>
					<view class="cu-form-group">
						<view class="title">入校时间</view>
						<picker @change="bindPickerNumUser" :value="userIndex" :range="numArr" range-key="value">
							<view class="picker" v-if="userForm.enrolledHour==='请输入具体时间'">
								请输入具体时间
							</view>
							<view class="picker" v-else>
								{{numArr[userIndex].value}}
							</view>
						</picker>
					</view>
					<view class="indextit"><text class="text-red">*</text>入校原因</view>
					<view class="cu-form-group align-start">
						<textarea disabled maxlength="-1" @input="textareaBInputUser" placeholder="请输入入校原因" v-model="userForm.enrolledReason"></textarea>
					</view>
				</form>
				<view class="temp-tip">
					<view>备注：</view>
					<view class="line">① 大型客车（20座及以上）进校需注明车辆荷载数，进出校校门、进出校时间、校内行驶路线及校内停放地点，否则将影响审核进度。</view>
					<view class="line">② 工程车及大型货车（车长超6米）工作日入校需校内单位线下提交由单位主要负责人签字、盖章的纸质申请单。</view>
				</view>
				<view class="padding flex flex-direction">
					<button class="cu-btn bg-blue lg" @click="submituserinfoapply()" :disabled="loadModal">提交申请</button>
				</view>
			</view>
		</block>
		<block v-if="TabCur==1">
			<view style="margin-top: 110rpx;">
				<view class="bg-white padding-lr">
					<view style="height: 10rpx;"></view>
					<apply-card v-for="(value,index) in result" :value="value" :key="index" @refresh="refreshList" @edit='toEdit'></apply-card>
				</view>

			</view>
		</block>

		<!-- 引用车牌组件 -->
		<plate-number ref="plate" v-model="plateNum" @showOrHide="showOrHide" @input="input"></plate-number>
		<view class="cu-modal" :class="modal=='DialogModal1'?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content">提示</view>
					<view class="action" @tap="hideModal">
						<text class="cuIcon-close text-black"></text>
					</view>
				</view>
				<view class="padding-xl">
					确定删除此车辆？
				</view>
				<view class="cu-bar bg-white justify-end">
					<view class="action">
						<button class="cu-btn line-gray text-green" @tap="cancel">取消</button>
						<button class="cu-btn bg-blue margin-left" @tap="del">确定</button>
					</view>
				</view>
			</view>
		</view>
		<view class="cu-modal" :class="modal=='DialogModal2'?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content">提示</view>
					<view class="action" @tap="hideModal">
						<text class="cuIcon-close text-black"></text>
					</view>
				</view>
				<view class="padding-xl">
					确定删除此人员申请？
				</view>
				<view class="cu-bar bg-white justify-end">
					<view class="action">
						<button class="cu-btn line-gray text-green" @tap="cancelU">取消</button>
						<button class="cu-btn  bg-blue margin-left" @tap="delU">确定</button>
					</view>
				</view>
			</view>
		</view>
		<view class="cu-modal" :class="modal=='DialogModal3'?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content">提示</view>
					<view class="action" @tap="hideModal">
						<text class="cuIcon-close text-black"></text>
					</view>
				</view>
				<view class="padding-xl">
					时间区域不能大于七天，请重新选择
				</view>
				<view class="cu-bar bg-white justify-end">
					<view class="action">
						<button class="cu-btn bg-blue" @tap="showPicker('rangeuser')">确定</button>
					</view>
				</view>
			</view>
		</view>
		<view class="cu-modal" :class="modal=='DialogModal4'?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content">提示</view>
					<view class="action" @tap="hideModal">
						<text class="cuIcon-close text-black"></text>
					</view>
				</view>
				<view class="padding-xl">
					时间区域不能大于七天，请重新选择
				</view>
				<view class="cu-bar bg-white justify-end">
					<view class="action">
						<button class="cu-btn bg-blue" @tap="showPicker('range')">确定</button>
					</view>
				</view>
			</view>
		</view>
		<view class="cu-load loading loadingfixed text-blue round" :class="loadModal?'show':''"></view>
		<w-picker mode="range" startYear="2020" endYear="2030" :current="true" @confirm="onConfirmUser($event,'range')"
		 @cancel="onCancel" ref="rangeuser"></w-picker>
		<w-picker mode="range" startYear="2020" endYear="2030" :current="true" @confirm="onConfirm($event,'range')" @cancel="onCancel"
		 ref="range"></w-picker>
		<w-picker mode="linkage" :value="defaultRegion1" :options="options" :level="2" :default-props="defaultProps1"
		 @confirm="onConfirmLinkage($event,'linkage')" @cancel="onCancel" ref="linkage"></w-picker>
		<w-picker mode="selector" :value="defaultRegion1" :options="auditPersons" :default-props="defaultProps2"
		  @confirm="onConfirmAuditPerson($event,'auditPerson')" @cancel="onCancel" ref="auditPerson"></w-picker>
		<w-picker mode="region" :value="defaultRegion" default-type="value" :hide-area="false" @confirm="onConfirmRegion($event,'region')"
		 @cancel="onCancel" ref="region"></w-picker>
		 <w-picker mode="region" :value="defaultRegion" default-type="value" :hide-area="false" @confirm="onConfirmPassRegion($event,'region')"
		  @cancel="onCancel" ref="region2"></w-picker>
		<multiple-select v-model="show" :default-selected="defaultSelected" :data="xiaoqu" @confirm="confirmXiaoqu"></multiple-select>
		<view class="modal" v-if="showNotice">
			<view class="mask">
			</view>
			<view class="container">
				<view class="title">申请须知</view>
				<view class="content">
					<view>1、确因工作需要进校的来访人员，按照“谁邀请、谁负责，谁主管、谁负责”的原则，由校内邀请人（联系人）通过本平台进行人员、车辆入校申请；</view>
					<view>2、本平台仅限于教职工使用，实行分类审核。人员和车辆（轿车、中小型货车、中小型客车）由校内申请人所在单位审核通过后，审核流程结束，访客凭有效身份证件和短信（含二维码链接）刷码进校；大型客车、特种车辆及大型货车（大型货车、中小型工程车、大型工程车非工作日进校）仍将推送至保卫与校园管理处审核，访客凭有效身份证件和短信（含二维码链接）刷码进校。以上若为团体进校仍将推送至保卫与校园管理处审核；</view>
					<view>3、特种车辆（包括但不限于叉车、吊车、铲车等）及大型货车（车长超过6m且总质量4500千克以上），原则上工作日不能进校；如有紧急情况，工作日入校需校内联络单位线下提交由单位主要负责人签字、盖章的纸质申请单（制式模板见官网《特种车辆及大型货车入校备案须知》）。进校时间应避开上下班（学）高峰期（7：30-8：30，13：50-14：20，17：30-18：20）；</view>
					<view>4、若访客车辆、人员较多，可选择批量导入，详情见填写界面；</view>
					<view>5、申请人所填访客信息、进校事由等必须真实准确，不得造假；</view>
					<view>6、如遇学校重大活动，将视情况动态管理；</view>
					<view>7、申请从事采访、拍摄、录制等活动人员进校，进校人员需随身携带校内申请单位发放的采访证或备案表（需备注校内联系人相关信息），以便联系；</view>
					<view>8、来访人员、车辆进入校园，自觉遵守相关校园交通管理规定，车辆进校后必须按照校园交通标志行驶，按照泊位或指定位置停放，严禁占用主干道或随意停放车辆，不得鸣笛，车速不得超过20km/h，且驾驶员联系方式置于车辆前挡风玻璃处醒目位置；</view>
				    <view>9、严禁上传涉密、违反法律法规及包含不良信息的文件。</view>
                    <view>10、如有其他疑问，请咨询保卫与校园管理处0551-63600083。</view>
				</view>
				<button :disabled="!canClick" :class="canClick && 'active'" type="default" @click="showNotice=false">已阅读{{ times>0 ? `(${times}s)`:''}}</button>
			</view>
		</view>
		<carNotice :show-notice.sync="showCarTip"></carNotice>
	</view>
</template>

<script>
	import multipleSelect from "@/components/multiple-select/multiple-select"
	import wPicker from "@/components/w-picker/w-picker.vue"
	import baseUrl from '../../api/api.js'
	import energy from '@/static/energy.png'
	import plateNumber from '@/components/plate-number/plateNumber.vue';
	import ClipboardJS from 'clipboard'
	import carNotice from "@/components/carNotice/index.vue"
	import applyCard from "@/components/applyCard/index.vue"
	


	let Base64 = require('js-base64').Base64
	export default {
		components: {
			plateNumber,
			wPicker,
			multipleSelect,
			carNotice,
			applyCard
		},
		data() {
			return {
				imageStyle:{
					"height": 100,	// 边框高度
					"width": 100,	// 边框宽度
					"border":{ // 如果为 Boolean 值，可以控制边框显示与否
						"color":"#eee",		// 边框颜色
						"width":"1px",		// 边框宽度
						"style":"solid", 	// 边框样式
						"radius":"10" 		// 边框圆角，支持百分比
					}
				},
				imageValue: [],
				defaultProps1: {
					label: "departName",
					value: "deptId",
					children: "departList"
				},
				defaultProps2: {
					label: "checkUserName",
					value: "checkUserGid",
					// children: "departList"
				},
				defaultSelected: [],
				index: 0,
				defaultRegion1: [],
				options: [],
				show: false,
				defaultRegion: ["340000", "340100", "340104"],
				userFormDateRange: '年/月/日',
				formDateRange: '年/月/日',
				numArr:  Array.from({length: 23}, (_, index) => index + 1).map(item => ({value: item+'时'})),
				carIndex: 0,
				loadModal: false,
				modal: null,
				isSumbituser: false,
				isSumbituserInfo: false,
				userForm: {
					checkUserName: '',
					checkUserGid: '',
					checkUserEmail: '',
					inviteCode: '',
					userInfo: [{
						userName: '',
						userPhone: '',
						applyArea: '',
						areaId: '',
						carType: 'CardType1',
						carTypeName: '身份证',
						cardNo: '',
						isDanger: 0,
						akCode:'',
						tripCode:'',
						naCode:'',
						hasCar: 0,
						carModelName: '',
						passPlace: [],
						passPlaceName: [],
					}],
					departName: '',
					deptId: '',
					concatName: '',
					concatPhone: '',
					campus: '',
					campusId: '',
					campusDoor: '',
					enrolledDate: '',
					endTime: '',
					enrolledHour: '请输入具体时间',
					enrolledReason: '',
					concatGid: '',
					concatName: '',
				},
				modalName: null,
				campus: null,
				CarModelList: [{
					name: '请选择车型',
					code: ''
				}],
				xqindex: -1,
				PXQindex: -1,
				xiaoqu: [],
				typeindex: 0,
				carType: [{
					name: '请选择身份类型',
					code: ''
				}],
				TabCur: '0',
				list: ['入校申请', '我的申请'],
				dialog: null,
				plateNum: '',
				keyword: '',
				result: [],
				numIndex: null,
				userIndex: 0,
				name: null,
				openId:null,
				ticket:null,
				energy: '', //新能源图标的地址
				canClick: false ,// 已阅读是否可以点击
				showNotice: false,
				times: process.env.NODE_ENV === 'production' ? 3 : 0,
				auditPersons: [],
				disableInput: false,
				inviteCode: '',
				params: {
					current: 1,
					size: 10
				},
				showCarTip: false,
			}
		},
		watch: {
			TabCur(val) {
				if(val == 1 && !this.result.length) {
					this.result = []
					this.getAppliedList()
				}
			}
		},
		onLoad() {
			if(process.env.NODE_ENV==='development') {
				this.openId = 'oDejQ1PUEBrk010l_hrXhzYgFLss'
			}
			this.getOPenid()
			let code = this.getParam(location.href, "code")

			if(code) {
				return this.wxLogin(code)
			}
			console.log('this.openId)', this.openId);
			if(!this.openId) {
				return this.getCode()
			}

			if(uni.getStorageSync('flag')) {
				uni.removeStorageSync('flag')
			} else {
				this.showNotice = false
				this.timer = setInterval(() =>{
					this.times--
					if(this.times<=0) {
						this.canClick = true
						clearInterval(this.timer)
					}
				}, 1000)
			}

			this.$nextTick(() => {
				this.clipboard = new ClipboardJS('.btn1');
				this.clipboard.on('success', (e) => {
					e.clearSelection();
					uni.showToast({
						title: '复制成功',
						icon: 'none'
					})
				});
			})
		},
		mounted() {
			this.$nextTick(() => {
				this.clipboard = new ClipboardJS('.btn1');
				this.clipboard.on('success', (e) => {
					e.clearSelection();
					uni.showToast({
						title: '复制成功',
						icon: 'none'
					})
				});
			})
		},
		onShow() {
			this.energy = energy;
			// this.disableInput = false
		},
		onReachBottom() {
			if(this.TabCur==1) {
				this.params.current++
				this.getAppliedList()
			}
		},
		onPullDownRefresh() {
			this.result = []
			this.getAppliedList()
		},
		methods: {
			toEdit(value) {
				this.TabCur = 0
				this.getAppliedList()
			},
			refreshList() {
				this.result = []
				this.params.current = 1
				this.getAppliedList()
			},
			uploadExcel() {
				uni.chooseFile({
					count: 6, //默认100
					extension:['.xlsx'],
					success:  (res) => {
						let tempFilePaths = res.tempFilePaths
						uni.uploadFile({
							url: baseUrl.baseUrl + "zkd/uploadExcel",
							filePath: tempFilePaths[0],
							name: 'file',
							formData: {
								'source': 1
							},
							success: (uploadFileRes) => {
								console.log('uploadFileRes', uploadFileRes);
								let res = JSON.parse(uploadFileRes.data)
								if(res.code===500) {
									return uni.showModal({
									 title: '提示',
									content: res.message,
									showCancel: false
			
									})
								}
								this.userForm.userInfo = [this.userForm.userInfo[0], ...res.data]
								this.userForm.userInfo && this.userForm.userInfo.forEach(user => {
									user.carType = user.cardType || user.carType
									user.carTypeName = user.cardTypeName
								})
								this.$forceUpdate()
							}
						});
					}
				});
			},
			toQrcode(qrCode) {
				uni.navigateTo({
					url: '/pages/qrcode/qrcode?see=1&' + qrCode
				})
			},
			reset() {
				this.userForm = {
					checkUserName: '',
					checkUserGid: '',
					checkUserEmail: '',
					inviteCode: '',
					userInfo: [{
						userName: '',
						userPhone: '',
						applyArea: '',
						areaId: '',
						carType: 'CardType1',
						carTypeName: '身份证',
						cardNo: '',
						isDanger: 0,
						akCode:'',
						tripCode:'',
						naCode:'',
						hasCar: 0,
						carModelName: '',
						passPlace: [],
						passPlaceName: [],
					}],
					departName: '',
					deptId: '',
					concatName: '',
					concatPhone: '',
					campus: '',
					campusId: '',
					campusDoor: '',
					enrolledDate: '',
					endTime: '',
					enrolledHour: '请输入具体时间',
					enrolledReason: '',
					concatGid: '',
				}
				this.userFormDateRange = '年/月/日'
				this.formDateRange = '年/月/日'
			},
			getInfoByCode() {
				uni.request({
					url: baseUrl.baseUrl + "zkd/invite/detail",
					data: {inviteCode: this.userForm.inviteCode},
					method: 'GET',
					header: {
						'content-type': 'application/x-www-form-urlencoded' //自定义请求头信息
					},
					success: (res) => {
						this.inviteInfo = res.data.data
						this.userForm = {...this.userForm, ...this.inviteInfo}

						this.userFormDateRange = `${this.inviteInfo.enrolledTime.split(' ')[0]}至${this.inviteInfo.endDate.split(' ')[0]}`;
						this.concatName = this.inviteInfo.concatName
						this.concatWage = this.inviteInfo.concatWage
						this.concatGid = this.inviteInfo.concatGid

						this.userForm.concatName = this.concatName
						this.userForm.concatWage = this.concatWage
						this.userForm.concatGid = this.concatGid
						this.$set(this.userForm.userInfo[0],'userName', this.inviteInfo.userName)
						this.$set(this.userForm.userInfo[0],'userPhone', this.inviteInfo.userPhone)
						this.$forceUpdate()
						console.log('this.userForm', this.userForm);
					}
				})
			},
			getOPenid(){
				this.getCARModel()
				this.getCampus()
				this.getCARType()
				this.getOrgan()
			},
			getCode() {
				let appid,redirectUri;
				if(process.env.NODE_ENV==='development') {
					appid = 'wxd5d6b165f5309cb6';
					redirectUri = encodeURIComponent('http://test.yumi.com:8770/assets/static/#/pages/visitor/visitor');
				} else {
					appid = 'wxac119bce1759d49f';
					redirectUri = encodeURIComponent('http://bwclf.ustc.edu.cn/assets/static/#/pages/visitor/visitor');
				}
				// 构建微信网页授权链接
				const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;
				// 重定向到授权链接
				window.location.href = authUrl;
			},
			wxLogin(code) {
				uni.request({
					url: baseUrl.baseUrl + "weixin/auth",
					data: {code: code},
					method: 'GET',
					header: {
						'content-type': 'application/x-www-form-urlencoded' //自定义请求头信息
					},
					success: (res) => {
						this.openId = res.data.data
						console.log('this.openId', this.openId);
						this.getOPenid()
					}
				})
			},
			chooseHasCar(num) {
				num.hasCar = num.hasCar==1?0:1
				if(num.hasCar===1) {
					num.carNumber = ''
					num.carModel = ''
					num.carModelName = ''
				}
			},
			handleDangerRadio(e,index){
				let val = e.detail.value;
				this.form.carInfo[index].isDanger = Number(val);
			},
			handleDangerRadio2(e,index){
				console.log(e,index);
				let val = e.detail.value;
				this.userForm.userInfo[index].isDanger = Number(val);
			},

			getParam(path, name) {
				var reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");
				if (reg.test(path))
					return decodeURIComponent(RegExp.$2.replace(/\+/g, " "));
				return "";
			},
			confirmXiaoqu(data) {
				if (this.campus) {
					this.userForm.campus = data.map((el) => el.label).join(" ");
					this.userForm.campusId = data.map((el) => el.value).join(",");
				} else {
					this.form.campus = data.map((el) => el.label).join(" ");
					this.form.campusId = data.map((el) => el.value).join(",");
				}
			},
			showPicker(type, index, name) {
				document.activeElement.blur();
				if (name) {
					this.name = name
				} else {
					this.name = null
				}
				console.log(index)
				if (index < 0) {
					this.numIndex = null
				} else {
					this.numIndex = index
				}
				this.modal = ''
				this.$refs[type].show();
			},
			onCancel(e){
				console.log(e)
			},
			onConfirmRegion(res, type) {
				if (this.numIndex > -1 && this.TabCur==1) {
					console.log(res.result)
					this.userForm.userInfo[this.numIndex].applyArea = res.result;
					let arr = []
					res.value.forEach(item => {
						arr.push(item)
					})
					this.userForm.userInfo[this.numIndex].areaId = arr.join(",");
				} else if(this.numIndex > -1 && this.TabCur==0) {
					let applyArea = res.result;
					let areaId = res.value.join(",");
					this.form.carInfo[this.numIndex].applyArea = applyArea;
					this.form.carInfo[this.numIndex].areaId = areaId;
				}
			},
			onConfirmPassRegion(res, type) {
				console.log('res', res);
				let areaId = res.value[2] || res.value[1];
				if (this.numIndex > -1 && this.TabCur==1) {
					this.userForm.userInfo[this.numIndex].passPlaceName.push({name: res.result, content: ''})
					this.userForm.userInfo[this.numIndex].passPlace.push(areaId)
				} else if(this.numIndex > -1 && this.TabCur==0) {
					this.form.carInfo[this.numIndex].passPlaceName.push({name: res.result, content: ''})
					this.form.carInfo[this.numIndex].passPlace.push(areaId)
				}
				console.log(this.form);
			},
			onConfirmLinkage(res, type) {
				this.userForm.departName = res.obj.col2.departName
				let arr = res.value
				this.userForm.deptId = arr[1];
				this.userForm.checkUserName = null;
				this.userForm.checkUserGid = null;
				this.userForm.checkUserEmail = null;
				this.getAuditPerson()
			},
			onConfirmAuditPerson(res, type) {
				if (this.name) {
					this.userForm.checkUserName = res.obj.checkUserName;
					this.userForm.checkUserGid = res.obj.checkUserGid;
					this.userForm.checkUserEmail = res.obj.checkUserEmail;
				} else {
					this.form.checkUserName = res.obj.checkUserName;
					this.form.checkUserGid = res.obj.checkUserGid;
					this.form.checkUserEmail = res.obj.checkUserEmail;
				}
				this.$forceUpdate()
			},

			onConfirmUser(res, type) {
				console.log('-----------------------------------------------------------------------------')
				console.log(new Date(res.value.split('至')[0]).getTime())
				console.log(new Date(res.value.split('至')[1]).getTime())
				var startU = new Date(res.value.split('至')[0]).getTime()
				var endU = new Date(res.value.split('至')[1]).getTime()
				console.log(Math.floor(startU / (24 * 3600 * 1000)))
				console.log(Math.floor(endU / (24 * 3600 * 1000)))
				console.log(Math.floor(endU / (24 * 3600 * 1000)) - Math.floor(startU / (24 * 3600 * 1000)))
				if (Math.floor(endU / (24 * 3600 * 1000)) - Math.floor(startU / (24 * 3600 * 1000)) >= 7) {
					this.modal = 'DialogModal3'
				} else {
					this.userForm.enrolledDate = res.value.split('至')[0]
					this.userForm.endTime = res.value.split('至')[1]
					this.userFormDateRange = res.value;
				}

			},
			onConfirm(res, type) {
				var start = new Date(res.value.split('至')[0]).getTime()
				var end = new Date(res.value.split('至')[1]).getTime()
				console.log(Math.floor(start / (24 * 3600 * 1000)))
				console.log(Math.floor(end / (24 * 3600 * 1000)))
				console.log(Math.floor(end / (24 * 3600 * 1000)) - Math.floor(start / (24 * 3600 * 1000)))
				if (Math.floor(end / (24 * 3600 * 1000)) - Math.floor(start / (24 * 3600 * 1000)) >= 7) {
					this.modal = 'DialogModal4'
				} else {
					this.form.enrolledDate = res.value.split('至')[0]
					this.form.endTime = res.value.split('至')[1]
					this.formDateRange = res.value;
				}
			},
			getAppliedList() {
				uni.request({
					url: baseUrl.baseUrl + "zkd/apply/record/page",
					data: {
						userOpenId: this.openId,
						...this.params
					},
					method: 'get',
					header: {
						'content-type': 'application/x-www-form-urlencoded' //自定义请求头信息
					},
					success: (res) => {
						console.log(res)
						if (res.data.code === 200) {
							this.result = this.result.concat(res.data.data.records)
						}
						setTimeout(uni.stopPullDownRefresh, 300)
					},
					fail(err) {
						setTimeout(uni.stopPullDownRefresh, 300)
					}
				})
			},
			//查询
			search() {
				this.result = []
				if (this.keyword === '') {
					uni.showModal({
						title: '提示',
						content: '请输入入校申请人姓名进行查询',
						showCancel: false
					});
				} else {
					var that = this
					uni.request({
						url: baseUrl.baseUrl + "applicationUserRecord/searchresult",
						data: {
							keyword: that.Trim(that.keyword)
						},
						method: 'POST',
						header: {
							'content-type': 'application/x-www-form-urlencoded' //自定义请求头信息
						},
						success(res) {
							console.log(res)
							if (res.data.code === 200) {
								let lstCar = []
								res.data.data.lstCar.forEach(item => {
									if (item.applyType !== undefined) {
										lstCar.push(item)
									}
								})
								let lstUser = []
								res.data.data.lstUser.forEach(item => {
									if (item.applyType !== undefined) {
										lstUser.push(item)
									}
								})
								that.result = lstCar.concat(lstUser)
								if (!that.result.length) {
									uni.showModal({
										title: '提示',
										content: '当前查无此人',
										showCancel: false
									});
								}
							}
						},
						fail(err) {
							console.log(err)
						}
					})

				}
			},
			//获取证件类型
			getCARType() {
				console.log(baseUrl.baseUrl)
				var that = this
				uni.request({
					url: baseUrl.baseUrl + "rest/dict/getdictlist",
					data: {
						code: 'CardType'
					},
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded' //自定义请求头信息
					},
					success(res) {
						that.carType = res.data.data
					},
					fail(err) {
						console.log(err)
					}
				})
			},
			//获取校外部门
			getOrgan() {
				var that = this
				uni.request({
					url: baseUrl.baseUrl + "rest/dept/getsysdeptlist",
					method: 'GET',
					header: {
						'content-type': 'application/x-www-form-urlencoded' //自定义请求头信息
					},
					success(res) {
						that.options = res.data.data
					},
					fail(err) {
						console.log(err)
					}
				})
			},
			getAuditPerson() {
				var that = this
				uni.request({
					url: baseUrl.baseUrl + "rest/dept/getOrgJobList",
					method: 'GET',
					header: {
						'content-type': 'application/x-www-form-urlencoded' //自定义请求头信息
					},
					data: {
						deptId: this.userForm.deptId
					},
					success(res) {
						console.log(res.data.data)
						that.auditPersons = null
						that.$nextTick(() => {
							that.auditPersons = res.data.data
						})
					},
					fail(err) {
						console.log(err)
					}
				})
			},
			//获取车型
			getCARModel() {
				var that = this
				uni.request({
					url: baseUrl.baseUrl + "rest/dict/getdictlist",
					data: {
						code: 'CarModel'
					},
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded' //自定义请求头信息
					},
					success(res) {
						that.CarModelList = res.data.data
					},
					fail(err) {
						console.log(err)
					}
				})
			},
			//获取Campus
			getCampus() {
				var that = this
				uni.request({
					url: baseUrl.baseUrl + "rest/dict/getdictlist",
					data: {
						code: 'Campus'
					},
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded' //自定义请求头信息
					},
					success(res) {
						let xiaoqu = []
						res.data.data.forEach(item => {
							var json = {
								label: item.name,
								value: item.code
							}
							xiaoqu.push(json)
						})
						that.xiaoqu = xiaoqu
					},
					fail(err) {
						console.log(err)
					}
				})
			},
			delCar(index) {
				this.modal = "DialogModal1"
				this.dialog = index
			},
			delUser(index) {
				console.log(index)
				this.modal = "DialogModal2"
				this.dialog = index
			},
			delU() {
				this.userForm.userInfo.splice(this.dialog, 1)
				this.modal = null
			},
			cancelU() {
				this.modal = null
			},
			del() {
				this.form.carInfo.splice(this.dialog, 1)
				this.modal = null
			},
			cancel() {
				this.modal = null
			},
			input(val) {
				this.userForm.userInfo[this.userIndex].carNumber = val ? val.trim():''
				console.log(val)
			},
			addUser() {
				var json = {
					userName: '',
					userPhone: '',
					areaId: '',
					areaInfo: '',
					applyArea: '',
					carType: 'CardType1',
					carTypeName: '身份证',
					cardNo: '',
					isDanger: 0,
					akCode:'',
					tripCode:'',
					naCode:'',
					passPlace: [],
					passPlaceName: [],
					hasCar: 0,
					carNumber: '',
					carModel: '',
					carModelName: '',
				}
				this.userForm.userInfo.push(json)

			},
			Trim(str){
			    return str.replace(/(^\s*)|(\s*$)/g, "");
			},
			submituserinfoapply() {
				console.log('submituserinfoapply', this.userForm);
				if(this.userForm.deptId.indexOf(',')!==-1){
					this.userForm.deptId=this.userForm.deptId.split(',')[1]
				}


				for (var i in this.userForm.userInfo) {
					if (this.userForm.userInfo[i].userName === '') {
						uni.showModal({
							title: '提示',
							content: '请输入来访申请人',
							showCancel: false
						});
						return
					} else if (this.userForm.userInfo[i].carType === '') {
						uni.showModal({
							title: '提示',
							content: '请选择证件类型',
							showCancel: false
						});
						return
					} else if (this.userForm.userInfo[i].cardNo==='') {
						uni.showModal({
							title: '提示',
							content: '请输入证件号码',
							showCancel: false
						});
						return
					} else if (this.userForm.userInfo[i].userPhone==='' || !this.$validate.isPhone(this.userForm.userInfo[i].userPhone)) {
						uni.showModal({
							title: '提示',
							content: '请输入正确的来访申请人电话',
							showCancel: false
						});
						return
					}  else if (this.userForm.userInfo[i].hasCar && (!this.userForm.userInfo[i].carModelName || !this.userForm.userInfo[i].carNumber)) {
						uni.showModal({
							title: '提示',
							content: '请输入车辆号码及选择车型',
							showCancel: false
						});
						return
					}
				}
				 if (this.userForm.departName === '') {
					uni.showModal({
						title: '提示',
						content: '请输入校内接待部门名称',
						showCancel: false
					});
					return
				} else if (this.userForm.checkUserName === '' || this.userForm.checkUserName === null) {
					uni.showModal({
						title: '提示',
						content: '请输入校审核人员',
						showCancel: false
					});
					return
				} else if (this.userForm.concatName === '') {
					uni.showModal({
						title: '提示',
						content: '请输入校内联系人',
						showCancel: false
					});
					return
				} else if (this.userForm.concatPhone === '') {
					uni.showModal({
						title: '提示',
						content: '请输入校内联系人电话',
						showCancel: false
					});
					return
				} else if (this.userForm.campusId === ''  || this.userForm.campusId === 'undefined') {
					uni.showModal({
						title: '提示',
						content: '请选择校区',
						showCancel: false
					});
					return
				} else if (this.userForm.enrolledTime === '') {
					uni.showModal({
						title: '提示',
						content: '请选择入校日期',
						showCancel: false
					});
					return
				} else if (this.userForm.enrolledReason === '') {
					uni.showModal({
						title: '提示',
						content: '请输入入校原因',
						showCancel: false
					});
					return
				} else {
					if (this.userForm.enrolledHour === '请输入具体时间') {
						this.userForm.enrolledHour = null
						return 
					}
					let arr = []
					let userinfo = JSON.parse(JSON.stringify(this.userForm.userInfo))
					let carNumber = 0
					userinfo.forEach(item => {
						if(item.hasCar) carNumber++
						item.userName = this.Trim(item.userName)
						item.userPhone = item.userPhone && item.userPhone.replace(/\s+/g,"")
						arr.push(item)
					})
					var that = this
					that.loadModal = true
					uni.request({
						url: baseUrl.baseUrl + "zkd/customer/apply",
						data: {
							...this.userForm,
							userInfo: JSON.stringify(arr),
							userOpenId: that.openId,
							userNum: arr.length,
							carNum: carNumber,
							hasCar: carNumber > 0,
							concatGid: that.getParam(location.href, "concatGid") || that.userForm.concatGid,
							concatName: that.getParam(location.href, "concatName") || that.userForm.concatName,
							concatWage: that.getParam(location.href, "concatWage") || that.userForm.concatWage
							
						},
						method: 'POST',
						header: {
							'content-type': 'application/json' //自定义请求头信息
						},
						success(res) {
							console.log(res)
							if (res.data.code === 200) {
								that.loadModal = false

								uni.showModal({
									content:'提交成功',
									showCancel:false,
									success: () => {
										that.result = []
										that.getAppliedList()
										that.reset()
									}
								})
							} else {
								uni.showModal({
									title: '提示',
									content: res.data.message,
									showCancel: false
								});
								that.loadModal = false
								if (!that.userForm.enrolledHour) {
									that.userForm.enrolledHour = '请输入具体时间'
								}
							}
						},
						fail(err) {
							that.loadModal = false
							console.log(err)
						}
					})
				}
			},
			textareaBInput(e) {
				this.form.enrolledReason = e.detail.value
			},
			textareaBInputUser(e) {
				this.userForm.enrolledReason = e.detail.value
			},
			bindPickerNum(e) {
				console.log(parseInt(e.detail.value))
				this.form.enrolledHour = parseInt(e.detail.value)
				this.index = parseInt(e.detail.value)
			},
			bindPickerNumUser(e) {
				console.log(e)
				console.log(this.userForm.enrolledHour)
				this.userForm.enrolledHour = parseInt(e.detail.value)
				this.userIndex = parseInt(e.detail.value)
			},
			CarModelChange(e) {
				console.log(e)
				console.log(e.detail.value)
				this.carIndex = e.detail.value
				this.userForm.userInfo[parseInt(e.currentTarget.dataset.id)].carModel = this.CarModelList[this.carIndex].code
				this.userForm.userInfo[parseInt(e.currentTarget.dataset.id)].carModelName = this.CarModelList[this.carIndex].name
				if(['CarModel6', 'CarModel7', 'CarModel4'].includes(this.CarModelList[this.carIndex].code)) {
					this.showCarTip = true
				}
			},
			clear(e) {
				console.log(e)
			},
			bindType(e) {
				this.typeindex = e.detail.value
				this.userForm.userInfo[parseInt(e.currentTarget.dataset.id)].carType = this.carType[this.typeindex].code
				this.userForm.userInfo[parseInt(e.currentTarget.dataset.id)].carTypeName = this.carType[this.typeindex].name
			},
			PickerSchool(val) {
				document.activeElement.blur();
				this.show = true
				this.campus = val === 'userForm' ? 'userForm' : null
				console.log(this.campus)
			},
			tabSelect(e) {
				this.TabCur = e.currentTarget.dataset.id;
				console.log(this.TabCur)
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 300
				});
			},
			/**
			 * @desc 车牌选择关闭和打开
			 */
			showOrHide(flag) {
				console.log(this.plateNum)
				if (this.carIndex === 0) {
					let value = {
						detail: {
							value: this.plateNum
						}
					}
					// this.getHistory(value)
				}
				console.log("被关闭了吗")
				console.log(flag)
				this.plateNum = ''
			},
			/**
			 * @desc 显示车牌选择器
			 */
			carInputClick(index,carNo) {
				this.userIndex = index
				this.$refs.plate.show(carNo);
			},
			getUserHistory(e, index) {
				if(this.disableInput) return ;
				if (index === 0) {
					console.log(index)
					var that = this
					uni.request({
						url: baseUrl.baseUrl + "zkd/search",
						data: {
							openId: that.openId,
							applySourse: 1,
							// keyword: e.detail.value
						},
						method: 'GET',
						header: {
							'content-type': 'application/x-www-form-urlencoded' //自定义请求头信息
						},
						success(res) {
							if (res.data.code === 200) {
								if (res.data.data !== '') {
									that.campus = 'userForm'
									that.userForm = res.data.data
									that.userForm.concatGid = that.concatGid || that.userForm.concatGid
									that.userForm.concatName = that.concatName || that.userForm.concatName
									that.userForm.concatWage = that.concatWage || that.userForm.concatWage
									that.userForm.checkUserName = that.userForm.checkUserName || null;
									that.userForm.checkUserGid = that.userForm.checkUserGid || null;
									that.userForm.checkUserEmail = that.userForm.checkUserEmail || null;
									var a = JSON.parse(res.data.data.userInfo)

									a.forEach(item => {
										for (var i = 0; i < that.carType.length; i++) {
											if (item.carType === that.carType[i].code) {
												item.carTypeName = that.carType[i].name
											}
											if(!item.isDanger) item.isDanger = 0;
										}
										if(item.applyArea===undefined){
											item.applyArea =''
										}
										if(item.areaId===undefined){
											item.areaId =''
										}
										item.akCode = ''
										item.tripCode = ''
										item.naCode = ''
									})
									that.userForm.userInfo = a
									that.defaultSelected = res.data.data.campusId.split(',')
									that.userForm.enrolledDateTime = res.data.data.enrolledHour||'请输入具体时间'
									that.userFormDateRange = res.data.data.enrolledDate + '至' + res.data.data.endTime
									console.log(that.userForm)
								}
							}
						},
						fail(err) {
							console.log(err)
						}
					})
				}
			},
		}
	}
</script>

<style lang="scss">
	.template-wrapper {
		padding-top: 30rpx;
		.btns {
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin: 0 20rpx 10rpx 20rpx;

			button {
				background: #004D95;
				color: #FFFFFF;
				height: 70rpx;
				line-height: 70rpx;
				display: flex;
				align-items: center;
				.icon {
					width: 30rpx;
					height: 30rpx;
					margin-right: 10rpx;
				}
			}
		}
		
	}
	.temp-tip {
		color: red;
		padding: 10rpx;
	
		.line {
			padding-left: 10rpx;
		}
	}
	.can-click {
		font-weight: bold;
		color: #0081ff;
		text-decoration: underline;
		margin-left: 10rpx;
	}
	.img-picker{
		padding-left: 30rpx;
		padding-bottom: 10px;
		background: #FFFFFF;
	}
	.bordre-top {
		border-top: 2rpx solid #eee;
	}
	.modal {
		.mask {
			position: fixed;
			top: 0;
			left: 0;
			width: 100vw;
			height: 100vh;
			background-color: rgba(0,0,0,0.6);
			z-index: 99999;
		}
		.container {
			position: fixed;
			top: 15%;
			left: 50%;
			transform: translateX(-50%);
			width: 650rpx;
			height: 70vh;
			background: #fff;
			border-radius: 16px;
			display: flex;
			flex-direction: column;
			align-items: center;
			z-index: 99999;

			.title {
				line-height: 2.6;
				font-size: 36rpx;
				font-weight: 800;
			}
			.content {
				padding: 20rpx;
				flex: 1;
				overflow-y: scroll;
				view {
					padding: 10rpx 0;
				}
			}
			button {
				width: 300rpx;
				margin: 20rpx;
				&.active {
					background-color: #0081ff;
					color: #FFFFFF;
				}
			}
		}
	}
	.indextit {
		padding: 20rpx;
	}
	.cu-form-group {
		min-height:64px !important;
	}
	.cu-form-group .title {
		width: 240rpx;
	}

	.carnumber {
		width: 460rpx;
	}

	.carnumber image {
		width: 70rpx;
		height: 40rpx;
		vertical-align: middle;
		margin-left: 10rpx;
		color: #000000;
	}

	.cu-form-group uni-picker .picker {
		text-align: left;
	}

	.btn-add {
		text-align: center;
		background: white;
		height: 42px;
		line-height: 42px;
		border-top: 1rpx solid #eee;
	}

	.tips {
		color: #888;
		padding: 10px;
		font-size: 24rpx;
		background: white;
	}

	.tips view {
		margin-top: 30rpx;
		text-indent: 56rpx;
		text-align: justify;
	}

	.loadingfixed {
		width: 200rpx;
		height: 200rpx;
		display: block;
		position: fixed;
		top: 50%;
		left: 50%;
		margin-top: -100rpx;
		margin-left: -100rpx;
		line-height: 100px;
		background: rgba(0, 0, 0, 0.1);
		display: none;
	}
</style>
